# crud/sys_organization.py
from sqlalchemy.orm import Session
from src.models.sys_organization import SysOrganization
from src.schemas.sys_organization import SysOrganizationCreate, SysOrganizationUpdate


def create_organization(db: Session, organization: SysOrganizationCreate):
    """
    创建单条组织记录。
    """
    db_organization = SysOrganization(**organization.dict())
    db.add(db_organization)
    db.commit()
    db.refresh(db_organization)
    return db_organization


def create_organizations(db: Session, organizations: list[SysOrganizationCreate]):
    """
    批量创建组织记录。
    """
    db_organizations = [SysOrganization(**org.dict()) for org in organizations]
    try:
        db.add_all(db_organizations)
        db.commit()
        for db_organization in db_organizations:
            db.refresh(db_organization)
        return db_organizations
    except Exception as e:
        db.rollback()
        raise e


def get_organization(db: Session, org_id: str):
    """
    根据 ID 获取组织记录。
    """
    return db.query(SysOrganization).filter(SysOrganization.id == org_id).first()


def get_organizations(db: Session, skip: int = 0, limit: int = 100):
    """
    获取组织记录列表。
    """
    return db.query(SysOrganization).offset(skip).limit(limit).all()


def update_organization(db: Session, org_id: str, organization: SysOrganizationUpdate):
    """
    更新组织记录。
    """
    db_organization = db.query(SysOrganization).filter(SysOrganization.id == org_id).first()
    if db_organization is None:
        return None
    update_data = organization.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_organization, key, value)
    db.commit()
    db.refresh(db_organization)
    return db_organization


def delete_organization(db: Session, org_id: str):
    """
    删除组织记录。
    """
    db_organization = db.query(SysOrganization).filter(SysOrganization.id == org_id).first()
    if db_organization is None:
        return None
    db.delete(db_organization)
    db.commit()
    return db_organization
